
<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <div class="form-trans">
                    <a-form-model style="width: calc(100% - 10px);" layout="vertical" ref="form"  :model="mdl" :rules="rules">
                        <a-row>
                            <a-col :span="24">
                                <a-form-model-item  :label="i18n('form.name','名称')" prop = "name">
                                    <a-input :placeholder="i18n('form.name','请输入名称','input')" v-model="mdl.name"/>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-model-item  :label="i18n('form.sourceBodef','源业务模型')">
                                    <rx-input-button width="100%" @click="openBoDef"
                                                     @change="changeBoDef"
                                                     v-model="JSON.stringify(sourceBodef)"
                                    ></rx-input-button>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item  :label="i18n('form.targetSolution','目标表单方案')">
                                    <rx-input-button width="100%" @click="openSolution"
                                                     @change="changeSolution"
                                                     v-model="JSON.stringify(targetSolution)"
                                    ></rx-input-button>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-model-item  :label="i18n('form.isEnable','是否启用')" prop = "status">
                                    <a-radio-group :options="enabledtions" v-model="mdl.status"/>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item  :label="i18n('form.transType','转换类型')" prop = "transType">
                                    <a-radio-group :options="tranType" v-model="mdl.transType"/>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                    </a-form-model>
                    <!--        主表            -->
                    <div class="form-trans-top">
                        <div class="form-trans-rule">
                            <a-tag color="#108ee9">{{i18n('form.mainTable','主表')}}</a-tag>
                            <span style="margin-right: 10px">{{ targetBodefData.name }} : {{bodefMainTable?bodefMainTable.label:""}}</span>
                            <a-button style="margin-right: 10px" @click="openConditionConfig('',true)">{{i18n('form.condition','选单条件')}}</a-button>
                            <template v-if="mdl.transType=='rule'">
                                {{i18n('form.groupRule','分组规则属性')}}：
                                <a-select v-model="mainGroupRule" option-filter-prop="children" style="width: 300px;" mode="multiple" @change="changeGroupRuleField($event,'',true)"  :options="sourceField"></a-select>
                            </template>
                        </div>
                        <div class="table-operator">
                            <a-button-group>
                                <a-button  @click="addConfig(targetBodefData.alias)" type="primary"><my-icon type="iconcommon-add"></my-icon></a-button>
                                <a-button @click="upRow(targetBodefData.alias)"><my-icon type="iconicon-test38"></my-icon></a-button>
                                <a-button @click="downRow(targetBodefData.alias)"><my-icon type="iconicon-test40"></my-icon></a-button>
                                <a-button  @click="removeConfig(targetBodefData.alias)"><my-icon type="iconVue3_delete"></my-icon></a-button>
                            </a-button-group>

                        </div>
                    </div>
                    <div class="form-trans-center">
                        <rx-grid
                            :ref="targetBodefData.alias"
                            :dataSource="mainFields"
                            :allowRowSelect="true"
                            :multiSelect="true"
                            :showPage="false"
                            :heightauto="true"
                            :columns="mappingColumns"
                        >
                            <span slot="field" slot-scope="{text,record,index}">
                                <a-select style="width: 100%;" v-model="record.field" :options="targetField"></a-select>
                            </span>
                            <span slot="mappingType" slot-scope="{text,record,index}">
                                        <a-select style="width: 100%;" v-model="record.mappingType" @change="typeChange(record)"
                                                  :options="mappingTypes"></a-select>
                                    </span>
                            <span slot="valueSource" slot-scope="{text,record,index}">
                                <template v-if="record.mappingType == 'field'">
                                    <a-select style="width: 100%;" v-model="record.valueSource" :options="sourceField"></a-select>
                                </template>
                                <template v-if="record.mappingType == 'constant'">
                                    <a-select style="width: 100%;" v-model="record.valueSource" :options="constantArr"></a-select>
                                </template>
                                <a-input style="width: 100%;" v-if="record.mappingType=='fixedVal' || record.mappingType=='template'"
                                         v-model="record.valueSource"
                                         />
                                <rx-input-button v-if="record.mappingType=='seqNo' "
                                                 @click="openSeqId($event,index,record)"
                                                 v-model="record.valueSource"></rx-input-button>
                                <rx-input-button v-if="record.mappingType=='script' "
                                                 @click="openScript($event,index,record,bodefMainTable[0].idValue,'yes',bodefMainTable)"
                                                 v-model="record.valueSource"></rx-input-button>
                            </span>
                        </rx-grid>
                        <div class="empty-grid" v-if="mainFields.length==0" ><a-empty/></div>
                    </div>
                    <!--           子表         -->
                    <div v-for="subBodef in  targetBodefData.boEntityList" >
                        <div class="form-trans-top">
                            <div class="form-trans-rule">
                                <a-tag color="#00BAAD">{{i18n('form.subTable','子表')}}</a-tag>
                                <span style="margin-right: 10px">{{ subBodef.name }}:</span>
                                <a-select allowClear style="margin-right: 10px;width: 150px" v-model="subRelationBo[subBodef.alias]"
                                          @change="selectSubTable(subBodef.alias)">
                                    <a-select-option  v-for="(field,index) in bodefSubTable" :key="index" :value="field.value" >
                                        {{field.label}}
                                    </a-select-option>
                                </a-select>
                                <a-button style="margin-right: 10px" @click="openConditionConfig(subBodef.alias)">{{i18n('form.condition','选单条件')}}</a-button>
                                <template v-if="mdl.transType=='rule'">
                                    {{i18n('form.groupRule','分组规则属性')}}：
                                    <a-select style="margin-right: 10px;width: 200px" v-model="subGroupRule[subBodef.alias]" option-filter-prop="children"  mode="multiple" @change="changeGroupRuleField($event,subBodef.alias,false)"  :options="sourceAllSubField[subtableRelation[subBodef.alias]]"></a-select>
                                    {{i18n('form.mergeRule','合并属性')}}：
                                    <a-select v-model="mergeRule[subBodef.alias]" style="width: 200px" @change="changeMergeRuleField($event,subBodef.alias)"  :options="sourceAllSubField[subtableRelation[subBodef.alias]]"></a-select>
                                </template>
                            </div>
                            <div class="table-operator">
                                <a-button-group>
                                    <a-button  @click="addConfig(subBodef.alias)" type="primary"><my-icon type="iconcommon-add"></my-icon></a-button>
                                    <a-button @click="upRow(subBodef.alias)"><my-icon type="iconicon-test38"></my-icon></a-button>
                                    <a-button @click="downRow(subBodef.alias)"><my-icon type="iconicon-test40"></my-icon></a-button>
                                    <a-button  @click="removeConfig(subBodef.alias)"><my-icon type="iconVue3_delete"></my-icon></a-button>
                                </a-button-group>
                            </div>
                        </div>
                        <div class="form-trans-center">
                            <rx-grid
                                :id="subBodef.alias"
                                :ref="subBodef.alias"
                                :dataSource="subFields[subBodef.alias]"
                                :allowRowSelect="true"
                                :multiSelect="true"
                                :showPage="false"
                                :columns="mappingColumns"
                                :heightauto="true"
                            >
                            <span slot="field" slot-scope="{text,record,index}">
                                       <a-select style="width: 100%;" v-model="record.field"
                                                 :options="targetAllSubField[subBodef.alias]"></a-select>
                                   </span>
                                <span slot="mappingType" slot-scope="{text,record,index}">
                                               <a-select style="width: 100%;" v-model="record.mappingType" @change="typeChange(record)"
                                                         :options="subMappingTypes"></a-select>
                                           </span>
                                <span slot="valueSource" slot-scope="{text,record,index}">
                                               <template v-if="record.mappingType === 'field'">
                                                   <a-select style="width: 100%;" v-model="record.valueSource"
                                                             :options="sourceAllSubField[subtableRelation[subBodef.alias]]"></a-select>
                                               </template>
                                               <template v-if="record.mappingType === 'mainField'">
                                                   <a-select style="width: 100%;" v-model="record.valueSource"
                                                             :options="sourceField"></a-select>
                                               </template>
                                               <template v-if="record.mappingType === 'constant'">
                                                   <a-select style="width: 100%;" v-model="record.valueSource"
                                                             :options="constantArr"></a-select>
                                               </template>
                                               <a-input
                                                   v-if="record.mappingType=='fixedVal' || record.mappingType=='template'"
                                                   v-model="record.valueSource"
                                               />
                                               <rx-input-button v-if="record.mappingType=='seqNo' "
                                                                @click="openSeqId($event,index,record)"
                                                                v-model="record.valueSource"></rx-input-button>
                                               <rx-input-button v-if="record.mappingType=='script' "
                                                                @click="openScript($event,index,record,subBodef.id,'no',subBodef)"
                                                                v-model="record.valueSource"></rx-input-button>
                                               </span>
                            </rx-grid>
                            <div class="empty-grid" v-if="getData(subBodef.alias)===0" ><a-empty/></div>
                        </div>
                    </div>
                </div>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
    import FormTransConfigApi from '@/api/form/core/formTransConfig'
    import {RxDialog,Util,Dialog,BaseFormModel} from "@lowcode/jpaas-common-lib";
    import FormBoDefApi from "@/api/form/bo/formBoDef";
    import formBoAttr from "@/api/form/bo/formBoAttr";
    import FormSolutionApi from "@/api/form/core/formSolution";
    import FormDbApi from "@/api/form/bo/formDb";
    import FormTranConditionConfig from "@/views/modules/form/core/FormTranConditionConfig.vue";
    import FormTransConfigScript from "@/views/modules/form/core/FormTransConfigScript.vue";


    export default {
        name: 'FormTransConfigEdit',
        mixins:[BaseFormModel],
        components: {
            RxDialog
        },
        computed: {
            table() {
                return this.$refs.table;
            },
            subMappingTypes(){
                let subMappingTypes = Util.deepClone(this.mappingTypes);
                subMappingTypes.unshift({label: this.i18n('mappingType.selectMain',"选择主表字段"), value:"mainField"})
                return subMappingTypes;
            }
        },
        data(){
            return {
                /**
                 * 子表列表，以及表格属性
                 */
                subTable: {},
                solutionDefId:"",
                sourceBodef: {},
                targetSolution: {},
                subRelationBo: {},
                settings: [],
                mdl: {
                    transType: "onetoone",
                    status: 1
                },
                rules: {
                    name: [{required: true, message: this.i18n('form.name','请输入名称','input'), trigger: 'change'}],
                    status: [{required: true, message: this.i18n('form.status','请选择状态','select'), trigger: 'change'}],
                    transType: [{
                        required: true,
                        message: this.i18n('form.transType','请选择转换类型','select'),
                        trigger: 'change'
                    }],
                },
                mappingColumns: [
                    {
                        title: this.$ti18('rxList.index', '序号'),
                        type: 'indexColumn',
                        width: 50,
                        dataIndex: 'serial',
                        scopedSlots: {customRender: 'serial'}
                    },
                    {
                        title: this.i18n("form.field",'目标属性'),
                        dataIndex: 'field',
                        scopedSlots: {customRender: 'field'}
                    },
                    {
                        title: this.i18n("form.mappingType",'映射类型'),
                        dataIndex: 'mappingType',
                        scopedSlots: {customRender: 'mappingType'}
                    },
                    {
                        title: this.i18n("form.valueSource",'值来源'),
                        dataIndex: 'valueSource',
                        scopedSlots: {customRender: 'valueSource'}
                    },

                ],
                enabledtions: [
                    {label: this.i18n('list.yes','是'), value: 1},
                    {label: this.i18n('list.no','否'), value: 0}
                ],
                tranType: [
                    {label: this.i18n('tranType.onetoone','一对一'), value: 'onetoone'},
                    {label: this.i18n('tranType.manytoone','多对一'), value: 'manytoone'},
                    {label: this.i18n('tranType.rule','根据分组合并规则生成'), value: 'rule'}
                ],
                mappingTypes: [
                    {label: this.i18n("mappingType.selectField","选择字段"), value: "field"},
                    {label: this.i18n("mappingType.constant","常量"), value: "constant"},
                    {label: this.i18n("mappingType.sourceId","源主键ID"), value: "sourceId"},
                    {label: this.i18n("mappingType.seqNo","流水号"), value: "seqNo"},
                    {label: this.i18n("mappingType.script","选脚本择字段"), value: "script"},
                    {label: this.i18n("mappingType.template","模板"), value: "template"},
                    {label: this.i18n("mappingType.fixedVal","固定值"), value: "fixedVal"},
                ],
                constantArr: [
                    {value: 'curDate', label: this.i18n("constant.curDate","当前时间")},
                    {value: 'curUserId', label: this.i18n("constant.curUserId","当前用户Id")},
                    {value: 'curUserName', label: this.i18n("constant.curUserName","当前用户姓名")},
                    {value: 'curDepId', label: this.i18n("constant.curDepId","当前部门Id")},
                    {value: 'curDepName', label: this.i18n("constant.curDepName","当前部门名称")},
                    {value: 'curInstId', label: this.i18n("constant.curInstId","当前机构Id")},
                    {value: 'curCompanyId', label: this.i18n("constant.curCompanyId","当前公司ID")},
                ].map(item=>{
                    return {...item,label:item.label.toLocaleUpperCase()}
                }),
                mainFields: [],
                mainGroupRule: [],
                subGroupRule: {},
                mergeRule: {},
                subFields: {},
                bodefData: [], // 源业务模型的主子表实体
                targetBodefData: {},//目标表单的主子表实体
                bodefSubTable: [],
                bodefMainTable: [],
                targetField: [],
                sourceField: [],
                sourceAllSubField: {},//所有源子表字段
                targetAllSubField: {},//所有目标子表字段
                subtableRelation: {},//子表关联关系
                //标准字段
                defField: ["ID_", "TENANT_ID_", "CREATE_BY_", "CREATE_TIME_", "UPDATE_BY_", "UPDATE_TIME_", "CREATE_DEP_ID_", "REF_ID_", "PARENT_ID_", "COMPANY_ID_", "INST_ID_", "INST_STATUS_","USER_INFO_"],
                //默认的标准字段
                defaultField:[
                    {label:this.i18n('defaultField.ID_','主键'),value:"ID_"},
                    {label:this.i18n('defaultField.REF_ID_','外键'),value:"REF_ID_"},
                    {label:this.i18n('defaultField.PARENT_ID_','父ID'),value:"PARENT_ID_"},
                    {label:this.i18n('defaultField.COMPANY_ID_','公司ID'),value:"COMPANY_ID_"},
                    {label:this.i18n('defaultField.TENANT_ID_','机构ID'),value:"TENANT_ID_"},
                    {label:this.i18n('defaultField.CREATE_BY_','创建人ID'),value:"CREATE_BY_"},
                    {label:this.i18n('defaultField.UPDATE_BY_','更新人ID'),value:"UPDATE_BY_"},
                    {label:this.i18n('defaultField.CREATE_DEP_ID_','创建部门ID'),value:"CREATE_DEP_ID_"},
                    {label:this.i18n('defaultField.CREATE_TIME_','创建时间'),value:"CREATE_TIME_"},
                    {label:this.i18n('defaultField.UPDATE_TIME_','更新时间'),value:"UPDATE_TIME_"},
                    {label:this.i18n('defaultField.INST_ID_','流程实例ID'),value:"INST_ID_"},
                    {label:this.i18n('defaultField.INST_STATUS_','流程实例状态'),value:"INST_STATUS_"},
                ],
            }
        },
        methods: {
            onload_(data) {;
                if (data) {
                    this.sourceBodef = {value: data.sourceBodefId, text: data.sourceBodefName}
                    this.targetSolution = {value: data.targetSolutionId, text: data.targetSolutionName}
                    this.settings = JSON.parse(data.settings)
                    for (let setting of this.settings){
                        if (setting.tableType == "main") {
                            this.mainFields = setting.mappingConfig
                            this.mainGroupRule = setting.groupRule?setting.groupRule:[];
                        }else {
                            this.mergeRule[setting.bodefAlias] = setting.mergeRule? setting.mergeRule : []
                            this.subGroupRule[setting.bodefAlias] = setting.groupRule ? setting.groupRule : [];
                            this.subFields[setting.bodefAlias] = setting.mappingConfig
                            this.subRelationBo[setting.bodefAlias] = setting.subBodefAlias;
                            //设置子表关联关系
                            this.$set(this.subtableRelation,setting.bodefAlias,setting.subBodefAlias)

                        }
                    }

                    this.loadBoDef(data.sourceBodefId)
                    this.handleTargetAllField(data.targetSolutionId)
                }
            },
            i18n(name,text,key){
                return this.$ti18(name,text,"formTransConfig",key);
            },
            openBoDef(vm) {
                var self = this;
                Dialog.openBoDefDialog({
                    curVm: this, widthHeight: ['1000px', '600px']
                }, function (data) {
                    if (self.solutionDefId && self.solutionDefId==data.id){
                        self.$message.error(self.i18n('msg.defNoSeem',"源业务模型不能与表单方案的业务模型相同！"));
                        return;
                    }
                    vm.setVal(data.id, data.name)
                    self.loadBoDef(data.id)
                })
            },
            openSolution(vm){
                var self = this;
                Dialog.openSolution({
                    curVm: this,multiSelect:false,  widthHeight: ['1000px', '600px'],
                    data:{
                        multiSelect:false,
                        allowTreeType:false
                    }
                }, function (data) {
                    if (self.mdl.sourceBodefId == data.bodefId){
                        self.$message.error(self.i18n('msg.defNoSeem',"源业务模型不能与表单方案的业务模型相同！"));
                        return;
                    }
                    self.solutionDefId=data.bodefId
                    vm.setVal(data.id, data.name)
                })
            },
            changeBoDef(val){
                if(!val){
                    this.mdl.sourceBodefId="";
                    this.mdl.sourceBodefName="";
                }
                var data=JSON.parse(val);
                this.mdl.sourceBodefId=data.value;
                this.mdl.sourceBodefName=data.text;
            },
            changeSolution(val){
                if(!val){
                    this.mdl.targetSolutionId="";
                    this.mdl.targetSolutionName="";
                }
                var data=JSON.parse(val);
                this.mdl.targetSolutionId=data.value;
                this.mdl.targetSolutionName=data.text;
                //重选目标表单方案时，清空setting
                this.settings = []
                this.loadTargetBoDef(data.value)
            },
            async loadBoDef(boDefId) {
                var res = await FormBoDefApi.getBosByDefId(boDefId)
                if (res){
                    this.bodefData = res.data;
                    this.bodefSubTable = res.data.filter(item => item.isMain != 'yes')
                    this.bodefMainTable = res.data.filter(item => item.isMain == 'yes')
                    var self = this
                    var main = "main"
                    let entIds = {main: this.bodefMainTable[0].idValue}
                    for (let item of this.bodefSubTable){
                        entIds[item.value]=item.idValue
                    }
                    var fields = await self.getFieldByEntIds(entIds)
                    self.sourceAllSubField={}
                    for (var key in fields){
                        if (key==main){
                            let sourceField = fields[key]
                            self.sourceField = [...sourceField,...self.defaultField].map(item=>{
                                // 将字段名转大写
                                item.value = item.value.toUpperCase()
                                return item;
                            })
                        }else {
                            let  subField = fields[key]
                            let upperCaseFields = [...subField,...self.defaultField].map(item=>{
                                // 将字段名转大写
                                item.value = item.value.toUpperCase()
                                return item;
                            })
                            self.$set(self.sourceAllSubField,key,upperCaseFields)
                        }
                    }
                }
            },
            async loadTargetBoDef(solutionId){
                var res =await  FormSolutionApi.getBoEntityBySolId(solutionId)
                this.targetBodefData = res.data;
                // 先将主表之间的映射放入settings
                let obj = {
                    "bodefName": this.targetBodefData.name,
                    "bodefAlias": this.targetBodefData.alias,
                    "entId": this.targetBodefData.id,
                    "tableType": "main",
                    "conditions": JSON.stringify({}),
                    "mappingConfig": [],
                }
                if (this.mdl.transType=="rule"){
                    obj.groupRule = []
                }
                this.settings.push(obj)
                var self = this
                //获取主表字段
                //let fields = await this.getFieldByDefAlias(this.targetBodefData.alias)
                let main="main"
                let entIds = {main: res.data.id}
                for (var subBodef of res.data.boEntityList) {
                    entIds[subBodef.alias] = subBodef.id
                }
                var fields = await self.getFieldByEntIds(entIds)
                for (var key in fields){
                    if (key==main){
                        self.targetField = fields[key]
                    }else {
                        self.targetAllSubField[key] = fields[key]
                        self.subFields[key] = []
                    }
                }
            },
            async handleTargetAllField(solutionId){
                var self = this
                var main = "main"
                var res =await FormSolutionApi.getBoEntityBySolId(solutionId)
                self.targetBodefData = res.data;
                let entIds = {main:res.data.id}
                for (var subBodef of res.data.boEntityList) {
                    entIds[subBodef.alias] = subBodef.id

                }
                var fields = await self.getFieldByEntIds(entIds)
                for (var key in fields){
                    if (key==main){
                        self.targetField = fields[key]
                    }else {
                        self.targetAllSubField[key] = fields[key]
                        // 默认给所有子表的表格，赋一个默认值
                        if(!self.subFields[key]){
                            self.subFields[key]=[];
                        }
                    }
                }
            },
            get(id){
                return FormTransConfigApi.get(id);
            },
            save(data,vm){
                let mainData = this.$refs[this.targetBodefData.alias].getData();
                // 收集主表映射条件
                for(let setting of this.settings){
                    if (setting["bodefAlias"] == this.targetBodefData.alias){
                        setting["mappingConfig"] = []
                        for (let mainFieldConfig of mainData){
                            let tip = this.i18n('form.mainTable','主表')+this.targetBodefData.name
                            if (!this.checkMapping(mainFieldConfig,setting,tip ,vm)){
                                return;
                            }
                        }
                    }
                }
                // 收集子表映射条件
                let subSettings = this.settings.filter(item=>item.tableType=="sub");
                for (let subSetting of subSettings){
                    let alias = subSetting["bodefAlias"]
                    if (!this.$refs[alias]){
                        break
                    }
                    let mappingConfig = []
                    if (Array.isArray(this.$refs[alias])){
                        mappingConfig = this.$refs[alias][0].getData();
                    }else {
                        mappingConfig = this.$refs[alias].getData();
                    }
                    subSetting["mappingConfig"] = []
                    for (let subFieldConfig of mappingConfig){
                        let tip = this.i18n('form.subTable','子表')+subSetting.bodefName
                        if (!this.checkMapping(subFieldConfig,subSetting,tip,vm)){
                            return;
                        }
                    }
                }
                this.mdl.settings = JSON.stringify(this.settings)
                return FormTransConfigApi.save(this.mdl);
            },
            checkMapping(config,setting,tip,vm){
                // 当目标属性和映射类型都为空时，点击确认后将数组中的这一条空的数据过滤掉
                // 当目标属性为空，映射类型不为空时，点击确认后，提示“主表xxxx，序号x，目标属性为空”或“子表xxxx，序号x，目标属性为空”
                if (!config.field && !config.mappingType){
                    return true;
                }else if (!config.field){
                    let msg = tip +","+this.$ti18('rxList.index', '序号')+config.serial+","+ this.i18n("form.field",'目标属性')+this.i18n('list.isEmpty','为空')
                    this.$message.error( msg);
                    vm.loading=false
                    return false;
                }else if (!config.mappingType){
                    let msg =  tip +","+this.$ti18('rxList.index', '序号')+config.serial+","+ this.i18n("form.mappingType",'映射类型')+this.i18n('list.isEmpty','为空')
                    this.$message.error(msg);
                    vm.loading=false
                    return false;
                } else  if (config.mappingType != "sourceId" && !config.valueSource){
                    let msg =  tip +","+this.$ti18('rxList.index', '序号')+config.serial+","+ this.i18n("form.valueSource","值来源")+this.i18n('list.isEmpty','为空')
                    this.$message.error(msg);
                    vm.loading=false
                    return false;
                }else {
                    setting["mappingConfig"].push(config)
                    return true;
                }
            },
            addConfig(refAlias) {
                if (!this.targetSolution){
                    this.$message.error( this.i18n('form.targetSolution','请选择目标表单方案','select'));
                    return;
                }
                if (!this.targetBodefData.alias){
                    this.$message.error( this.i18n('form.targetSolution','请选择目标表单方案','select'));
                    return;
                }
                if (!refAlias){
                    this.$message.error(this.i18n('msg.nosubform','请选择子表！'));
                    return;
                }
                var boDefId = this.mdl.sourceBodefId;
                if (!boDefId) {
                    this.$message.error( this.i18n('msg.noSourceDef','请选择源表业务模型！'));
                    return;
                }
                if (Array.isArray(this.$refs[refAlias])){
                    this.$refs[refAlias][0].addRow({});
                }else {
                    this.$refs[refAlias].addRow({});
                }
                this.$forceUpdate();
            },
            removeConfig(refAlias) {
                if (Array.isArray(this.$refs[refAlias])){
                    this.$refs[refAlias][0].removeRows();
                }else {
                    this.$refs[refAlias].removeRows();
                }
                this.$forceUpdate();
            },
            upRow(refAlias) {
                if (Array.isArray(this.$refs[refAlias])){
                    this.$refs[refAlias][0].moveUp();
                }else {
                    this.$refs[refAlias].moveUp();
                }
            },
            downRow(refAlias) {
                if (Array.isArray(this.$refs[refAlias])){
                    this.$refs[refAlias][0].moveDown();
                }else{
                    this.$refs[refAlias].moveDown();
                }
            },
            typeChange(record){
                record.valueSource=""
            },
            async getFieldByEntIds(entIds){
                var data = await formBoAttr.getByEntIds(entIds)
                for (var key in data){
                    if (!Array.isArray(data[key])) {
                        continue
                    }
                    data[key] = data[key].map(item=>{
                        return {
                            label:item.comment,
                            value:item.fieldName?item.fieldName:item.name,
                        }
                    })
                }
                return data;
            },
            selectSubTable(alias) {
                let value = this.subRelationBo[alias];
                if (value) {
                    this.subtableRelation[alias] = value;
                    this.buildSetting(alias,value)
                }
            },
            buildSetting(bodefAlias,subBodefAlias){
                let obj ={
                    "tableType":"sub",
                    "mappingConfig":[],
                    "conditions": JSON.stringify({}),
                }
                let subObj = this.targetBodefData.boEntityList.filter( subObj => subObj.alias == bodefAlias);
                let bodef = this.bodefSubTable.filter( bodef => bodef.value == subBodefAlias)
                if (subObj.length > 0 && bodef.length > 0){
                    obj.id = subObj[0].id;
                    obj.bodefName = subObj[0].name;
                    obj.bodefAlias = subObj[0].alias;
                    obj.subBodefAlias = bodef[0].value;
                    obj.subBodefName = bodef[0].label;
                }
                if (this.settings.length > 0){
                    let index = this.settings.findIndex(item => item.bodefAlias == bodefAlias)
                    if (index > -1){
                        this.settings[index] = obj
                    }else {
                        this.settings.push(obj)
                    }
                }else {
                    this.settings.push(obj)
                }

            },
            openConditionConfig(alias,isMain){
                var config = {};
                var setting = []
                if (isMain){
                    setting = this.settings.filter(setting => setting.tableType=="main");
                    var boDefId = this.mdl.sourceBodefId;
                    if (!boDefId) {
                        this.$message.warning(this.i18n('msg.noform','请选择表单！'));
                        return;
                    }
                    config = {boDefId : boDefId,entId:this.bodefMainTable[0].idValue}
                }else {
                    setting = this.settings.filter(setting => setting.bodefAlias == alias)
                    if (setting.length == 0){
                        this.$message.warning(this.i18n('msg.nosubform','请选择子表！'));
                        return;
                    }
                    let subTableList=this.bodefSubTable.filter(item=>item.value==setting[0].subBodefAlias)
                    config = {bodefAlias : setting[0].subBodefAlias,entId:subTableList[0].idValue}
                }

                if (!(setting.length > 0)){
                    this.$message.warning(this.i18n('msg.noSourceDef','请选择源业务模型'));
                    return;
                }
                var conditionConfig = setting[0].conditions?setting[0].conditions:JSON.stringify({});
                var conf= {
                    curVm:this,
                    data:{config:conditionConfig,...config},
                    max:true,
                    component:FormTranConditionConfig,
                    title: this.i18n('form.conditionConfig',"选单条件配置")
                };
                Util.open(conf,function(action,data){
                    if(action!='ok')return;
                    setting[0].conditions=data;
                })
            },
            changeGroupRuleField(data,alias,isMain){
                var setting = []
                if (isMain) {
                    setting = this.settings.filter(setting => setting.tableType == "main");
                    this.mainGroupRule = data;
                } else {
                    setting = this.settings.filter(setting => setting.bodefAlias == alias)
                    //this.subGroupRule[alias] = data;
                    this.$set(this.subGroupRule, alias, data);
                    this.$forceUpdate();
                }
                setting[0].groupRule = data;
            },
            changeMergeRuleField(data,alias){
                let setting = this.settings.filter(setting => setting.bodefAlias == alias)
                this.$set(this.mergeRule, alias, data);
                setting[0].mergeRule = data;
                this.$forceUpdate();
            },
            openSeqId(vm, index, record) {
                Dialog.openSysSeqIdDialog({
                    curVm: this, widthHeight: ['1300px', '600px']
                }, function (self, data) {
                    vm.setVal(data.alias, data.name);
                    record.valueSource = data.alias;

                })
            },
            openScript(vm, index, record,entId,isMain) {
                var self = this;
                var baseConf = {
                    "curVm": self,
                    component: FormTransConfigScript,
                    title: this.i18n('msg.scriptConfig',"脚本配置"),
                    widthHeight: ['800px', '500px'],
                    data: {
                        value: record.valueSource,
                        entId: entId,
                        isMain: isMain
                    }
                };
                // 如果为子表添加主实体信息
                if (isMain=="no"){
                    baseConf.data["mainEntId"] = this.bodefMainTable[0].idValue;
                }
                Util.open(baseConf, function (action, data) {
                    if (action == 'ok') {
                        record.valueSource = data;
                    }
                });
            },
            getData(refAlias){
                let num = 0
                if(!refAlias || !this.subFields || !this.subFields[refAlias]){
                    return num;
                }
                return this.subFields[refAlias].length;
            }
        },
    }
</script>
<style scoped>
.form-trans{
    display: flex;
    flex-direction: column;
    height: 100%;
    padding:0px 20px;
    box-sizing: border-box;
}
.form-trans-top{
    display: flex;
    align-items: center;
}
.form-trans-center{
    margin-bottom: 20px;
}
.form-trans-rule{
    display: flex;
    align-items: center;
    flex: 1;
}
.form-trans>>>.ant-form-item{
    margin-bottom: 10px!important;
}
.empty-grid{
    border: 1px solid #d9d9d9;
    border-top: none;
    padding: 20px;
}
</style>
